<?php

namespace App\Models\V1;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Lauthz\Facades\Enforcer;
use Lauthz\Models\Rule;
use function genTree;

class SysPermission extends BaseModel
{
    use HasFactory;
    public $timestamps = true;
    protected $table="sys_permission";
    protected $fillable=['parent_id','name','icon','is_cache','is_frame','query','menu_type','method','order_num','path','state','component','perms','visible'];
    protected $hidden=[];

    protected function getIdentifier($id)
    {
        return "box_admin_permission_".$id;
    }

    public function getIsCacheAttribute()
    {
        return (string)$this->attributes['is_cache'];
    }

    public function getIsFrameAttribute()
    {
        return (string)$this->attributes['is_frame'];
    }

    public function getStateAttribute()
    {
        return (string)$this->attributes['state'];
    }


    public function getHiddenAttribute()
    {
        return $this->attributes['hidden']?true:false;
    }


    /**
     * 获取用户ID权限菜单
     * @param $id
     * @return array|array[]
     */
    public function getPermissionMenu($user_id) :array
    {
        $role_model=new SysRole();
        $roles =  $role_model->getRolesFromCache($user_id);

        $permissions_array= [];
        $permission_model=new SysPermission();
        foreach ($roles as $value) {
            list($node,$permissions) = $permission_model->getPermissions($value);
            $permissions_array=array_merge($permissions_array,$node);
        }
        //->whereIn('id',$permissions_array)
        //权限修改修改
//        $list=$permission_model->whereIn('menu_type',['M','C'])->where('state',1)->select("id","name",'parent_id','path','order_num','component','menu_type','visible as hidden','is_cache','icon')->orderBy('order_num','asc')->get()->toArray();
        $list=$permission_model->whereIn('id',$permissions_array)->whereIn('menu_type',['M','C'])->where('state',1)->select("id","name",'parent_id','path','order_num','component','menu_type','visible as hidden','is_cache','icon')->orderBy('order_num','asc')->get()->toArray();
        //封装数据
        $data=[];
        foreach($list as $key=>$row){
            $data[$key]=$row;
            $data[$key]['meta']=[
                'icon'=>$row['icon'],
                'link'=>"",
                'noCache'=>$row['is_cache']?true:false,
                'title'=>$row['name']
            ];
            $data[$key]['children']=[];
            if(!$row['component']){
                $data[$key]['component']="Layout";
            }
            if($row['menu_type']=="M"){
                if($row['parent_id']==0){//最上层
                    $data[$key]['path']="/".$row['path'];
                }else{
                    $data[$key]['component']="ParentView";
                }
            }
        }
        $data=genTree($data,'parent_id');
        return $data;
    }

    /**
     * 根据角色id获取权限
     * @param $id
     * @return array
     */
    public function getPermissions($id) : array
    {
        $id = $this->getIdentifier($id);
        $permissions = Enforcer::guard('box_admin')->getPermissionsForUser($id);

        if(empty($permissions)) return [[],[]];
        $node[] = array_map(function ($value)  {
            return (int)$value[3];
        },$permissions);

        sort($node[0]);
        return [$node[0],$permissions];
    }

    //获取所有权限
    public function getAllPermission($keyword = null)
    {
        $list=$this->query()
            ->where('state',1)
            ->select('id as value','name as label','id','parent_id')
            ->get()
            ->toArray();
        return $list=genTree($list,'parent_id','children');
    }

    /**
     * 设置用户权限
     * @param $nodeId
     * @param $id
     */
    public function setPermissions($nodeId,$id)
    {
        $id = $this->getIdentifier($id);
        $permissions = $this->query()->where('state', 1)
            ->whereIn('id', $nodeId)
            ->get()->toArray();
        Enforcer::guard('box_admin')->deletePermissionsForUser($id);
        foreach ($permissions as $value) {
            $path=$value['perms'];
            if(empty($path)){
                $path="";
            }
            Enforcer::guard('box_admin')->addPermissionForUser($id, $path, "*",$value['id']);
        }
        $rule_model=new Rule([],'box_admin');
        $rule_model->refreshCache();
    }

    /**
     * 删除所属角色的权限
     * @param $id
     */
    public function delPermissions($id){
        $id = $this->getIdentifier($id);
        Enforcer::guard('box_admin')->deletePermissionsForUser($id);
        $rule_model=new Rule([],'box_admin');
        $rule_model->refreshCache();
    }
}
